package com.zfei.gfb;

import com.google.gson.*;
import com.zfei.gfb.device.GsonConfig;
import com.zfei.gfb.device.InboxConf;
import com.zfei.gfb.util.Httpc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.unit.DataSize;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.MultipartConfigElement;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author fgh
 */
@Import({GsonConfig.class})
@EnableTransactionManagement
@EnableOpenApi
@MapperScan("com.zfei.gfb.dao")
@SpringBootApplication(exclude = { JacksonAutoConfiguration.class })
public class WebApplication implements JsonSerializer<Json> {


    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }


    @Bean
    public InboxConf inboxConf() {
        return new InboxConf();
    }

    @Bean
    public Httpc httpc() {
        return Httpc.getInstance();
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个数据大小
        factory.setMaxFileSize(DataSize.ofMegabytes(200)); // KB,MB
        // 总上传数据大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(400));
        return factory.createMultipartConfig();
    }

    @Bean
    public HttpMessageConverters customConverters() {

        Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        gsonHttpMessageConverter.setGson(
                new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd")
                        .registerTypeAdapter(Json.class, new WebApplication())
                        .create());
        messageConverters.add(gsonHttpMessageConverter);

        return new HttpMessageConverters(true, messageConverters);
    }

    @SuppressWarnings("deprecation")
    @Override
    public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
        final JsonParser parser = new JsonParser();
        return parser.parse(json.value());
    }
}
